<template>
    <el-form :model="form" ref="form" :rules="rules" class="form">
        <el-form-item class="form-item" prop="username">
            <el-input placeholder="用户名/手机" v-model="form.username" @focus="hideErrMsg('username')">
            </el-input>
        </el-form-item>

        <el-form-item class="form-item" prop="password">
            <el-input
                placeholder="密码"
                type="password"
                v-model="form.password"
            >
            </el-input>
        </el-form-item>

        <p class="form-text">
            <nuxt-link to="#">忘记密码</nuxt-link>
        </p>

        <el-button class="submit" type="primary" @click="handleLoginSubmit">
            登录
        </el-button>
    </el-form>
</template>

<script>
    import {login} from './user'
    export default {
        data() {
            return {
                form: {
                    username: "13800138000",
                    password: "123456",
                },
                rules: {
                    username: [
                        {
                            required: true,
                            message: "请输入信息",
                            trigger: "blur",
                        },
                    ],
                    password: [
                        {
                            required: true,
                            message: "请输入信息",
                            trigger: "blur",
                        },
                        {
                            min: 6,
                            message: "密码不能小于六位",
                            trigger: "blur",
                        },
                    ],
                },
            };
        },
        methods: {
            async handleLoginSubmit() {
                const isValid = await this.$refs.form.validate();

                if (isValid) {
                    const res = await login(this.form);

                    if (res && res.data.token) {
                        this.$message.success("登录成功");
                        this.$store.commit('userstore/setUserInfo', res.data)
                    }
                }
            },
            hideErrMsg(propName) {
                // 当输入框聚焦需要清理当前输入项的错误提示
                // 优化体验
                // 拿到当前 form 对象
                // 调用里面 clearValidate 函数
                // 传入希望清理的 prop
                this.$refs.form.clearValidate(propName)
            }
        },
    };
</script>

<style scoped lang="less">
    .form {
        padding: 25px;
    }

    .form-item {
        margin-bottom: 20px;
    }

    .form-text {
        font-size: 12px;
        color: #409eff;
        text-align: right;
        line-height: 1;
    }

    .submit {
        width: 100%;
        margin-top: 10px;
    }
</style>